<template>
  <div class="container">
    <el-row type="flex" justify="space-between">
      <div class="main">
        <!-- 写游记 -->
        <h2>发表新攻略</h2>
        <p>分享你的个人游记，让更多人看到哦！</p>
        <el-form ref="form" :model="form">
          <el-form-item>
            <el-input v-model="form.title" placeholder="请输入标题" />
          </el-form-item>
          <!-- 富文本部分 -->
          <div class="fu">
            <client-only>
              <vue-editor
                v-model="form.content"
                :editorToolbar="customToolbar"
                @image-added="handleImageAdded"
                :config="config"
                style="height:458px;margin-bottom:50px"
              />
            </client-only>
          </div>
          <el-form-item label="出发城">
            <el-autocomplete
              :fetch-suggestions="getCityList"
              v-model="form.city"
              @select="selectCity"
              :trigger-on-focus="false"
              :highlight-first-item="true"
              placeholder="请搜索游玩城市"
              class="el-autocomplete"
            />
          </el-form-item>
        </el-form>
        <div class="creat-button">
          <el-button @click="addPost" type="primary" style="padding:9px 15px;font-size:12px">发布</el-button>
          <span>
            或者
            <a @click="addDraft" href="javascript:;">保存到草稿</a>
          </span>
        </div>
      </div>

      <!-- 草稿箱部分 -->
      <div class="aside">
        <div class="draft-box">
          <h4 class="draft-title">草稿箱({{$store.state.history.postList.length }})</h4>
          <div class="draft-list">
            <div
              v-for="(item,index) in $store.state.history.postList"
              :key="index"
              class="draft-item"
            >
              <div @click="getDraft(index)" class="draft-post-title">
                {{ item.title }}
                <span class="iconfont el-icon-edit" />
              </div>
              <p>{{ $moment(item.created_at).format('YYYY-MM-DD hh:mm') }}</p>
            </div>
          </div>
        </div>
      </div>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        title: "",
        content: "",
        city: ""
      },
      id: "",
      customToolbar: [
        ["bold", "italic", "underline", "strike"],
        [{ header: 1 }, { header: 2 }],
        ["image"]
      ],
      theme: "snow",
      config: {
        //   上传图片的配置
        uploadImage: {
          url: `${this.$axios.defaults.baseURL}/upload`,
          name: "files",
          hearders: {
            Authorization: "Bearer " + this.$store.state.user.userInfo.token
          },
          uploadSuccess: (res, insert) => {
            console.log(res);
            const file = res.data[0];
            insert(this.$axios.defaults.baseURL + file.url);
          }
        }
      }
    };
  },
  computed: {
    draftList() {
      return this.$store.state.history.postList;
    }
  },
  watch: {
    draftList() {
      return this.$store.state.history.postList;
    }
  },
  methods: {
    handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      var formdata = new FormData();
      formdata.append("files", file);
      //			发送ajax上传图片
      this.$axios({
        url: "/upload",
        method: "post",
        data: formdata
      })
        .then(res => {
          console.log("这里是上传图片到编辑器", res);
          const { data } = res.data;
          //         	这里需要拼接基准路径,然后才能将图片显示出来
          let url = this.$axios.defaults.baseURL + data.url;
          //下面是固定写法，将图片插入到编辑器中
          Editor.insertEmbed(cursorLocation, "image", url);
          //有一个必须要做的事情就是重置上传组件
          resetUploader();
        })
        .catch(err => {
          //这里是捕获错误
          console.log(err);
        });
    },
    // 获取草稿
    getDraft(index) {
      this.form = { ...this.$store.state.history.postList[index] };
      this.form.city = this.form.cityName;
    },
    // 保存草稿
    addDraft() {
      this.addPost().then(res => {
        const { data } = res.data;
        console.log("data", data);
        this.$store.commit("history/addPostlist", { ...data });
      });
      console.log("草稿数据", this.$store.state.history.postList);
    },
    async getCityList(value, showList) {
      // 获取真正的搜索建议
      const cityList = await this.searchCity(value);
      showList(cityList);
    },
    searchCity(value) {
      return this.$axios({
        url: "/airs/city",
        params: {
          name: value
        }
      }).then(res => {
        const { data } = res.data;
        const citys = data.map(element => {
          return {
            ...element,
            value: element.name
          };
        });
        const cityList = citys.filter(element => element.sort);
        // 准备建议数据,然后时候 showList 回调返回到 组件当中显示
        return cityList;
      });
    },
    selectCity(item) {
      this.form.city = item.name;
    },
    // 发布文章
    addPost() {
      // 获取富文本框的内容
      // this.form.content = this.$refs.vueEditor.editor.root.innerHTML;
      console.log("查看5", this.form);
      // 获取token
      const token = this.$store.state.user.userInfo.token;
      // 如果没有 token  证明用户还没有登录,直接跳转到登录页
      if (!token) {
        this.$message({
          message: "请先登录",
          type: "error"
        });
        this.$router.push({
          path: "/user/login"
        });
        return;
      }
      // 如果输入框为空，则不发送请求
      if (this.form.title === "" || this.form.city === "") {
        this.$message({
          type: "warning",
          message: "请填写完整"
        });
        return;
      }
      // 发送请求
      return this.$axios({
        url: "/posts",
        method: "post",
        data: this.form,
        headers: {
          Authorization: "Bearer " + token
        }
      }).then(res => {
        console.log("查看6", res);
        this.$message({
          type: "success",
          message: "提交成功"
        });
        // const { data } = res.data;
        //情况输入框的数据
        this.form = {
          title: "",
          content: "",
          city: ""
        };
        return res;
      });
    }
  }
};
</script>

<style lang="less" scoped>
.container {
  width: 1000px;
  margin: 0 auto;
  padding: 20px 0;
  .main {
    width: 750px;
    h2 {
      font-weight: 400;
      font-size: 22px;
      margin-bottom: 10px;
    }
    p {
      font-size: 12px;
      color: #999;
      margin-bottom: 10px;
    }
    .creat-button {
      span {
        margin-left: 10px;
        font-size: 14px;
        a {
          color: orange;
          &:hover {
            text-decoration: underline;
          }
        }
      }
    }
    .fu {
      margin-bottom: 70px;
    }
  }
  .aside {
    width: 200px;
    .draft-box {
      border: 1px solid #ddd;
      padding: 10px;
    }
    .draft-title {
      margin-bottom: 10px;
      font-weight: 400;
      color: #666;
    }
    .draft-list {
      .draft-item {
        font-size: 14px;
        margin-bottom: 5px;
        .draft-post-title {
          cursor: pointer;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          &:hover {
            color: orange;
            text-decoration: underline;
          }
          span {
            margin-left: 5px;
          }
        }
        p {
          color: #999;
        }
      }
    }
  }
}
</style>